package cn.demoncat.util.web.entity;

import org.apache.commons.io.IOUtils;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * 可重复读取的 RequestWrapper
 * <p>
 * 1、只支持 JSON 请求；如果是 FormData 请求，会丢失请求参数（Request类判断InputStream已被读取时，不会重新获取ParameterMap）
 *
 * @author 延晓磊
 * @since 2023年02月08日
 */
public class RepeatableServletRequestWrapper extends HttpServletRequestWrapper {

    private final byte[] body;

    /**
     * 构建 RequestWrapper，读取 InputStream
     *
     * @param request
     *
     * @throws IOException
     */
    public RepeatableServletRequestWrapper(HttpServletRequest request) throws IOException {
        super(request);
        // 读取
        body = IOUtils.toByteArray(super.getInputStream());
    }

    /**
     * 获取 BufferedReader
     *
     * @return BufferedReader，因为每次调用都会新建，所以能无限读取
     */
    @Override
    public BufferedReader getReader() {
        return new BufferedReader(new InputStreamReader(getInputStream()));
    }

    /**
     * 获取 InputStream
     *
     * @return InputStream，因为每次调用都会新建，所以能无限读取
     */
    @Override
    public ServletInputStream getInputStream() {
        return new RepeatableServletInputStream(body);
    }
}